package tbdp.tool;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import tbdp.tool.common.Constants;

import javax.annotation.Nullable;
import java.io.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Created by xbkaishui on 16/10/16.
 * 兼容上海文本文件读取逻辑
 * 处理单个文件 生成的新文件后缀是.txt
 */
public class CleanWorker implements Callable<Boolean> {

    private static Logger logger = Logger.getLogger(CleanWorker.class);

    private String inputFile;
    private String marketType;
    private File outputBaseDir;

    public CleanWorker(String outputBaseDir, String inputFile, String marketType) {
        this.outputBaseDir = new File(outputBaseDir);
        this.inputFile = inputFile;
        this.marketType = marketType;
        try {
            FileUtils.forceMkdir(this.outputBaseDir);
        } catch (IOException e) {
        }
    }

    @Override
    public Boolean call() throws Exception {
        boolean flag = true;
        try {
            File dataFile = new File(inputFile);
            String filePath = dataFile.getAbsolutePath();
            //读取dbf 文件
            List<List<String>> finalResult = null;
            if (filePath.contains("mktdt00.txt")) {
                logger.info(Thread.currentThread().getName() + " handler txt  file " + filePath);
                finalResult = TxtFileReader.readFile(dataFile, Constants.charset);
            } else {
                logger.info(Thread.currentThread().getName() + " handler dbf file " + filePath);
                List<Map<String, String>> datas = DBFReader.readDbfFile(dataFile, Constants.charset);
//            logger.debug(inputFile + " datas:\t" + datas);
                //修复文件
                finalResult = Repair.repair(datas, this.marketType);
            }

            //回写数据
            String name = dataFile.getName();
            String outFileName = generateOutFileName(name);
            writeOutPut(finalResult, outFileName);
        } catch (Throwable e) {
            flag = false;
            logger.error("CleanWorker error " + inputFile, e);
        }

        return flag;
    }

    /**
     * 把数据回写到文件
     *
     * @param finalResult
     * @param outFileName
     */
    private void writeOutPut(List<List<String>> finalResult, String outFileName) {
        File outFile = new File(outputBaseDir, outFileName);
        logger.info("write out " + outFile.getAbsolutePath());
        Collection<String> lines =
                Collections2.transform(finalResult, new Function<List<String>, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable List<String> input) {
                        return Joiner.on("|").join(input);
                    }
                });
        OutputStream oos = null;
        try {
            oos = new FileOutputStream(outFile);
            PrintWriter writer = new PrintWriter(oos);
            IOUtils.writeLines(lines, null, writer);
            writer.flush();
        } catch (Exception e) {
            logger.error("write out put file error " + outFile.getAbsolutePath(), e);
        } finally {
            IOUtils.closeQuietly(oos);
        }
    }


    protected String generateOutFileName(String name) {
        return name.substring(0, name.indexOf(Constants.zipSuffix)) + Constants.txtSuffix;
    }
}
